import { useState, useEffect } from 'react'

export default function App() {
  /**
   * useMemo
   *    缓存昂贵的计算
   *    useMemo函数会在渲染期间执行，所以它仅适用于 纯函数 场景。
   */
  /**
   * 外部的组件传递一个 key 属性给内部的组件
   */
  const [position, setPosition] = useState({ x: 0, y: 0 })
  const [canMove, setCanMove] = useState(true)

  //   const handleMove = useCallback( function handleMove2(e) {
  //     if (canMove) {
  //       setPosition({ x: e.clientX, y: e.clientY });
  //     }
  //   }, [canMove])
  //   useEffect(() => {
  //     window.addEventListener('pointermove', handleMove);
  //     return () => window.removeEventListener('pointermove', handleMove);
  //   }, [handleMove]);

  useEffect(() => {
    function handleMove(e) {
      setPosition({ x: e.clientX, y: e.clientY })
    }

    if (!canMove) {
      window.removeEventListener('pointermove', handleMove)
    } else {
      window.addEventListener('pointermove', handleMove)
    }
    return () => window.removeEventListener('pointermove', handleMove)
  }, [canMove])

  return (
    <>
      <label>
        <input type="checkbox" checked={canMove} onChange={(e) => setCanMove(e.target.checked)} />
        是否允许移动
      </label>
      <hr />
      <div
        style={{
          position: 'absolute',
          backgroundColor: 'pink',
          borderRadius: '50%',
          opacity: 0.6,
          transform: `translate(${position.x}px, ${position.y}px)`,
          pointerEvents: 'none',
          left: -20,
          top: -20,
          width: 40,
          height: 40,
        }}
      />
    </>
  )
}
